<template>
  <div class="user-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>
            <el-breadcrumb separator-class="el-icon-arrow-right">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item>用户管理</el-breadcrumb-item>
              <el-breadcrumb-item>账户管理</el-breadcrumb-item>
            </el-breadcrumb></span
          >
        </div>
      </template>
      <div>
        <el-button
          type="primary"
          size="small"
          @click="
            drawer = true;
            eventType = 'add';
          "
          >创建用户</el-button
        >
        <el-button type="danger" size="small" @click="batchDelete"
          >批量删除</el-button
        >
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
          v-model="searchKey"
          size="small"
          style="width: 250px; margin-left: 15px"
        >
        </el-input>
      </div>
      <el-table
        ref="multipleTable"
        :data="userList"
        tooltip-effect="dark"
        v-loading="loading"
        :stripe="true"
        :height="maxHeight"
        style="width: 100%; top: 15px"
        @selection-change="accountSelectionChange"
      >
        <el-table-column type="selection" width="55" fixed="left">
        </el-table-column>

        <el-table-column label="电话号码" width="120" fixed="left">
          <template #default="scope"
            ><el-link
              type="primary"
              href="javascript:;"
              @click="userEdit(scope.row)"
              >{{ scope.row.telephone }}</el-link
            ></template
          >
        </el-table-column>
        <el-table-column
          label="姓名"
          width="120"
          show-overflow-tooltip
          fixed="left"
        >
          <template #default="scope">{{ scope.row.username }}</template>
        </el-table-column>
        <el-table-column label="用户类型" width="120"
          ><template #default="scope">
            <el-tag
              v-if="scope.row.userType === userType.AdminType"
              type="warning"
              >管理员
            </el-tag>
            <el-tag
              v-else-if="scope.row.userType === userType.BaiyeType"
              type="info"
              >百叶管理员
            </el-tag>
            <el-tag v-else effect="plain">其他 </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="updateTime"
          label="最近更新"
          show-overflow-tooltip
        >
        </el-table-column>
        <el-table-column
          label="添加权限"
          show-overflow-tooltip
          fixed="right"
          width="80"
          ><template #default="scope"
            ><el-switch
              :loading="scope.row.switchLoading"
              v-model="scope.row.addpower"
              active-color="#13ce66"
              inactive-color="#ff4949"
              :active-value="1"
              :inactive-value="0"
              @change="addpowerChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="80">
          <template #default="scope">
            <el-popconfirm
              confirmButtonText="确定"
              cancelButtonText="取消"
              icon="el-icon-info"
              cancelButtonType="danger"
              iconColor="red"
              title="确定删除该账号信息吗？"
              @confirm="handleDelete(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="mini">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 30px">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[15, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :disabled="loading"
        >
        </el-pagination>
      </div>
    </el-card>
  </div>
  <accountDrawer
    :drawer="drawer"
    :handleClose="handleClose"
    :eventType="eventType"
    :editAccount="editAccount"
  />
</template>

<script lang="ts">
import { UserService, Account } from "@/api/user";
import { reactive, toRefs, watch, computed } from "vue";
import accountDrawer from "./accountDrawer.vue";
import { UserType } from "./consts";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";
import { ElMessageBox } from "element-plus";
import Code from "@/consts/common";

export default {
  name: "User",
  components: { accountDrawer },
  setup() {
    const store = useStore();
    const selectdAccount: number[] = [];
    const getUserList = (
      page: number = 1,
      size: number = 15,
      keyword?: string
    ) => {
      store.dispatch("User/getUserList", { page, size, keyword });
    };

    let data = reactive({
      currentPage: computed(() => store.state.User.page),
      pageSize: computed(() => store.state.User.size),
      searchKey: "",
      drawer: false,
      eventType: "add",
      userId: 0,
      editAccount: new Account(),
      maxHeight: document.documentElement.clientHeight - 280,
      userList: computed(() => store.state.User.userList),
      total: computed(() => store.state.User.total),
      loading: computed(() => store.state.User.loading),
      userType: UserType,
      selectdAccount: selectdAccount,
      handleDelete: (id: number) => {
        UserService.deleteAccount([id]).then((res) => {
          if (res.code == 200) {
            ElMessage({
              showClose: true,
              message: "删除账户成功",
              type: "success",
            });
            getUserList(1, data.pageSize, data.searchKey);
          }
        });
      },
      handleSizeChange: (size: number) => {
        console.log(size);

        store.dispatch("User/pageSizeChange", {
          page: data.currentPage,
          size,
          keyword: data.searchKey,
        });
      },
      handleCurrentChange: (page: number) => {
        store.dispatch("User/pageChange", {
          page,
          size: data.pageSize,
          keyword: data.searchKey,
        });
      },
      handleClose: () => {
        data.drawer = false;
      },
      userEdit: (selectdAccount: Account) => {
        data.drawer = true;
        data.eventType = "edit";
        let item = new Account();
        item.id = selectdAccount.id;
        item.username = selectdAccount.username;
        item.userType = selectdAccount.userType;
        item.userTypeValue = selectdAccount.userTypeValue;
        item.telephone = selectdAccount.telephone;
        item.addpower = selectdAccount.addpower;
        item.addpowerValue = selectdAccount.addpowerValue;
        data.editAccount = item;
      },
      accountSelectionChange: (selectedAccounts: Account[]) => {
        data.selectdAccount = [];
        selectedAccounts.map((item) => {
          data.selectdAccount.push(item.id);
        });
      },
      batchDelete: () => {
        if (data.selectdAccount.length == 0) {
          ElMessage({
            showClose: true,
            message: "至少选择一条",
            type: "error",
          });
          return;
        }
        ElMessageBox.confirm("此操作将永久删除这些用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            UserService.deleteAccount(data.selectdAccount).then((res) => {
              if (res.code == Code.CODE_SUCCESS) {
                ElMessage({
                  showClose: true,
                  message: "删除账户成功",
                  type: "success",
                });
                getUserList(data.currentPage, data.pageSize, data.searchKey);
              }
            });
          })
          .catch(() => {});
      },
      addpowerChange: (account: Account) => {
        if (account.id != null) {
          account.switchLoading = true;
          UserService.addAccount(account).then((res) => {
            if (res.code == Code.CODE_SUCCESS) {
              ElMessage({
                showClose: true,
                message: "权限已变更",
                type: "success",
              });
            } else {
              if (account.addpower == 1) {
                account.addpower = 0;
              } else {
                account.addpower = 1;
              }
            }

            account.switchLoading = false;
          });
        }
      },
    });
    const getHeight = () => {
      data.maxHeight = document.documentElement.clientHeight - 280;
    };
    watch(
      () => data.searchKey,
      (newValue, oldVlaue) => {
        getUserList(1, data.pageSize, newValue);
      }
    );

    getUserList(data.currentPage, data.pageSize);

    window.addEventListener("resize", getHeight, false);
    return {
      ...toRefs(data),
    };
  },
};
</script>

<style lang="less" scoped>
.el-divider--horizontal {
  margin: 15px 0;
}
</style>